/*
 * Duration.java
 *
 * Created on July 10, 2006, 4:21 PM
 *
 */

package org.vcboard.model;

import org.apache.log4j.Logger;

/**
 * @author Josh
 */
public class Duration
{
   private static Logger log = Logger.getLogger(Duration.class);
   
   private static final int MINUTE = 60;
   private static final int HOUR = MINUTE * 60;
   private static final int DAY = HOUR * 24;
   
   private long duration = -1;
   private int days = 0;
   private int hours = 0;
   private int minutes = 0;
   private int seconds = 0;
   
   /** Creates a new instance of Duration */
   public Duration()
   {
   }
   
   /**
    * Creates a new Duration object and sets the 
    * number of seconds elapsed
    *
    * @param long duration number of seconds
    */
   public Duration(long duration)
   {
      setDuration(duration);
   }

   /**
    * Ged the number of seconds elasped
    *
    * @return number of seconds 
    */
   public long getDuration()
   {
      return duration;
   }

   /**
    * Sets the number of seconds elapsed
    *
    * @param long duration number of seconds
    */
   public void setDuration(long duration)
   {
      this.duration = duration;
   }
   
   /**
    * Return the duration formatted as HH:mm:ss
    *
    * @return the duration formatted as HH:mm:ss
    */
   public String getTime()
   {
      toString();
      StringBuffer str = new StringBuffer();
      
      int tHours = (days * 24) + hours;
      if (tHours > 0)
      {
         str.append(String.format("%1$02d:", tHours));
      }
      
      str.append(String.format("%1$02d:", minutes));
      str.append(String.format("%1$02d", seconds));
      
      return str.toString();
   }
   
   /**
    * Format the elapsed time
    *
    * @return the time elapsed
    */
   public String toString()
   {
      StringBuffer output = new StringBuffer();
      
      if (getDuration() != -1)
      {
         long working = getDuration();

         if (working >= DAY)
         {
            days = (int) (working / DAY);
            working -= DAY * days;

            output.append(days + "d, ");
         }

         if (working >= HOUR)
         {
            hours = (int) (working / HOUR);
            working -= HOUR * hours;

            output.append(hours + "h, ");
         }

         if (working >= MINUTE)
         {
            minutes = (int) (working / MINUTE);
            working -= MINUTE * minutes;

            output.append(minutes + "m, ");
         }

         seconds = (int) working;
         output.append(seconds + "s");

         //log.info("Total Duration: " + output);
      }
      else
      {
         output.append("...");
      }
      
      return output.toString();
   }
}
